package com.study.testSpringBoot.concurrent;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;

import org.springframework.stereotype.Component;

@Component
public class DataModelAtomic {
	//存放数据
	private AtomicStampedReference<Map<String,Integer>> asr = new AtomicStampedReference<Map<String,Integer>>(new HashMap<>(), 0);
	
	public void addData(String key) {
		//原数据
		Map<String, Integer> smap = asr.getReference();
		//目标记录
		Map<String, Integer> dmap = new HashMap<>();
		if(!smap.isEmpty()) {
			Set<Entry<String,Integer>> set = smap.entrySet();
			for(Entry<String,Integer> et : set) {
				if(et.getKey().equals(key)) {
					dmap.put(et.getKey(), et.getValue() + 1);
				}else {
					dmap.put(et.getKey(), et.getValue());
				}
			}
		}else {
			dmap.put(key, 1);
		}
		//使用原子变量的自旋锁设置值
		asr.compareAndSet(smap, dmap, asr.getStamp(), asr.getStamp() + 1);
		System.out.println("---当前数据模型中的数据："+asr.getReference().get("ceshi"));
	}
	
	
	public Map<String, Integer> getAndDelData(){
		Map<String, Integer> smap = asr.getReference();
		Map<String, Integer> dmap = new HashMap<>();
		asr.compareAndSet(smap, dmap, asr.getStamp(), asr.getStamp() + 1);
		return smap;
	}
}
